Grokking Tree Coding Patterns for Interviews
Rate this course
Ask Author
Contribute
Back to course home

0% completed

Vote For New Content
Introduction
Course Overview
Basics of Tree
Introduction to Tree
Types of Tree
BST Traversal Techniques
BST Operations
Level Order Traversal Pattern (easy)
Introduction to Level Order Traversal Pattern
Reverse Level Order Traversal (easy)
Solution: Reverse Level Order Traversal
Find Largest Value in Each Tree Row (medium)
Solution: Find Largest Value in Each Tree Row
Maximum Width of Binary Tree (medium)
Solution: Maximum Width of Binary Tree
Maximum Level Sum of a Binary Tree (medium)
Solution: Maximum Level Sum of a Binary Tree
Zigzag Traversal (medium)
Solution: Zigzag Traversal
Even Odd Tree (medium)
Solution: Even Odd Tree
N-ary Tree Level Order Traversal (hard)
Solution: N-ary Tree Level Order Traversal
Introduction to Tree Depth Pattern
Maximum Depth (or Height) of Binary Tree (easy)
Solution: Maximum Depth (or Height) of Binary Tree
Minimum Depth of a Binary Tree (easy)
Solution: Minimum Depth of a Binary Tree
Balanced Binary Tree (easy)
Solution: Balanced Binary Tree
Tree Diameter (easy)
Solution: Tree Diameter
Maximum Depth of N-ary Tree (easy)
Solution: Maximum Depth of N-ary Tree
Find maximum depth of subtree (medium)
Solution: Find maximum depth of subtree
Introduction to Root to Leaf Path Pattern
Binary Tree Paths (easy)
Solution: Binary Tree Paths
Sum of Root To Leaf Binary Numbers (easy)
Solution: Sum of Root To Leaf Binary Numbers
Insufficient Nodes in Root to Leaf Paths (medium)
Solution: Insufficient Nodes in Root to Leaf Paths
Smallest String Starting From Leaf (medium)
Solution: Smallest String Starting From Leaf
Pseudo-Palindromic Paths in a Binary Tree (medium)
Solution: Pseudo-Palindromic Paths in a Binary Tree
All Paths for a Sum (medium)
Solution: All Paths for a Sum
Sum of Path Numbers (medium)
Solution: Sum of Path Numbers
Path With Given Sequence (medium)
Solution: Path With Given Sequence
Count Paths for a Sum (medium)
Solution: Count Paths for a Sum
Introduction to Leaf Processing Pattern
Sum of Left Leaves (easy)
Solution: Sum of Left Leaves
Leaf-Similar Trees (easy)
Solution: Leaf-Similar Trees
Check if all leaves are at same level (medium)
Solution: Check if all leaves are at same level
Delete Leaves With a Given Value (medium)
Solution: Delete Leaves With a Given Value
Deepest Leaves Sum (medium)
Solution: Deepest Leaves Sum
Introduction to Tree View Pattern
Right View of a Binary Tree (medium)
Solution: Right View of a Binary Tree
Top View Of the Binary Tree (medium)
Solution: Top View Of the Binary Tree
Bottom View Of the Binary Tree (medium)
Solution: Bottom View Of the Binary Tree
Boundary of Binary Tree (medium)
Solution: Boundary of Binary Tree
Introduction to Comparison of Two Trees Pattern
Symmetric Tree (easy)
Solution: Symmetric Tree
Mirror Image Trees (medium)
Solution: Mirror Image Trees
Subtree of Another Tree (easy)
Solution: Subtree of Another Tree
Isomorphic Trees (medium)
Solution: Isomorphic Trees
Introduction to Serialize and Deserialize Tree Pattern
Serialize and Deserialize BST (medium)
Solution: Serialize and Deserialize BST
Verify Preorder Serialization of a Binary Tree (medium)
Solution: Verify Preorder Serialization of a Binary Tree
Create Binary Tree From Descriptions (medium)
Solution: Create Binary Tree From Descriptions
Serialize and Deserialize N-ary Tree (hard)
Solution: Serialize and Deserialize N-ary Tree
Solution: Find Largest Value in Each Tree Row

Problem Statement

Given the root of a binary tree, return an array containing the largest value in each row of the tree (0-indexed).

Examples

Example 1

  • Input: root = [1, 2, 3, 4, 5, null, 6]
  • Expected Output: [1, 3, 6]
Image
  • Justification:
    • The first row contains 1. The largest value is 1.
    • The second row has 2 and 3, and the largest is 3.
    • The third row has 4, 5, and 6, and the largest is 6.

Example 2

  • Input: root = [7, 4, 8, 2, 5, null, 9, null, 3]
  • Expected Output: [7, 8, 9, 3]
Image
  • Justification:
    • The first row contains 7, and the largest value is 7.
    • The second row has 4 and 8, and the largest is 8.
    • The third row has 2, 5, and 9, and the largest is 9.
    • The fourth row has 3, and the largest is 3.

Example 3

  • Input: root = [10, 5]
  • Expected Output: [10, 5]
  • Justification:
    • The first row has 10, and the largest value is 10.
    • The second row contains 5, and the largest is 5.

Constraints:

  • The number of nodes in the tree will be in the range [0, 104].
  • -231 <= Node.val <= 231 - 1

Solution

To solve this problem, we need to determine the maximum value at each level (row) of the binary tree. A level order traversal (breadth-first search) is ideal for this task. By traversing each level of the tree one by one, we can find the maximum value in each row and add it to the result list. This approach ensures that every level is fully processed before moving to the next.

Using level order traversal is efficient because it only requires a single pass through the tree, processing each node exactly once. This makes it an optimal solution with a linear time complexity, proportional to the number of nodes in the tree.

Step-by-Step Algorithm

  1. Initialize Result List:

    • Create result as an empty list to store the largest values of each row.
  2. Check for Empty Tree:

    • If root is null, return the empty result list.
  3. Initialize Queue:

    • Create a queue and add root to start level order traversal.
  4. Process Each Level:

    • While the queue is not empty:
      • Determine the number of nodes at the current level (levelSize).
      • Set maxVal to Integer.MIN_VALUE.
  5. Process Each Node at Current Level:

    • For each node in the current level:
      • Dequeue a node, update maxVal with the maximum of maxVal and the node's value.
      • If the node has a left child, enqueue it.
      • If the node has a right child, enqueue it.
  6. Store Largest Value:

    • After processing all nodes at the current level, add maxVal to result.
  7. Repeat for All Levels:

    • Continue until the queue is empty.
  8. Return Result:

    • Return result containing the largest values in each row.

Algorithm Walkthrough

Input: root = [1, 2, 3, 4, 5, null, 6]

Image
  1. Initialize:

    • result = [] (to store largest values)
    • queue = [1] (start with the root node)
  2. Level 1:

    • levelSize = 1 (1 node at this level), maxVal = -∞ (initialize to smallest value)
    • Process Node 1:
      • Dequeue node 1 → queue = []
      • maxVal = max(-∞, 1) = 1 (update because -∞ is less than 1)
      • Enqueue children 2 and 3 → queue = [2, 3]
    • Store Largest Value of Level 1:
      • Add 1 to result → result = [1]
  3. Level 2:

    • levelSize = 2 (2 nodes at this level), maxVal = -∞ (reset for new level)
    • Process Node 2:
      • Dequeue node 2 → queue = [3]
      • maxVal = max(-∞, 2) = 2 (update because -∞ is less than 2)
      • Enqueue children 4 and 5 → queue = [3, 4, 5]
    • Process Node 3:
      • Dequeue node 3 → queue = [4, 5]
      • maxVal = max(2, 3) = 3 (update because 3 is greater than 2)
      • Enqueue child 6 → queue = [4, 5, 6]
    • Store Largest Value of Level 2:
      • Add 3 to result → result = [1, 3]
  4. Level 3:

    • levelSize = 3 (3 nodes at this level), maxVal = -∞ (reset for new level)
    • Process Node 4:
      • Dequeue node 4 → queue = [5, 6]
      • maxVal = max(-∞, 4) = 4 (update because -∞ is less than 4)
    • Process Node 5:
      • Dequeue node 5 → queue = [6]
      • maxVal = max(4, 5) = 5 (update because 5 is greater than 4)
    • Process Node 6:
      • Dequeue node 6 → queue = []
      • maxVal = max(5, 6) = 6 (update because 6 is greater than 5)
    • Store Largest Value of Level 3:
      • Add 6 to result → result = [1, 3, 6]
  5. Return Result:

    • Final output: [1, 3, 6] (largest values from each row).

Code

Java
Saved to Cloud

. . . .

Complexity Analysis

Time Complexity

  • The algorithm performs a level-order traversal (BFS) of the binary tree. Each node in the tree is visited exactly once, and all nodes are added to the queue at most once.
  • Therefore, the time complexity is , where n is the number of nodes in the binary tree.

Space Complexity

  • The space complexity is mainly determined by the queue used for the level-order traversal. In the worst case, the queue could hold all nodes at the deepest level of the tree. For a balanced binary tree, the maximum number of nodes at the deepest level is approximately n/2, where n is the total number of nodes.
  • Therefore, the space complexity is in the worst case.
Find Largest Value in Each Tree Row (medium)
Maximum Width of Binary Tree (medium)
Mark as Completed

On this page

Problem Statement

Examples

Example 1

Solution

Step-by-Step Algorithm

Algorithm Walkthrough

Code

Complexity Analysis

Time Complexity

Space Complexity